package main

import (
	"errors"
	"fmt"
	"nway_dsr/nway_dsr/utils/nway_db_connection"
	"os"
	"strings"
)

func InsertFailKey(keyword string) error {
	var sql string

	sql = "INSERT INTO fail_keys (keyword)" +
		" VALUES ($1);"

	//logger.Debug(sql)
	NwayConn := nwayconnection.NewDb()
	stmt, err := NwayConn.GetConn().Prepare(sql)
	defer stmt.Close()
	if err != nil {
		fmt.Println(err)
		return err
	}

	_, err = stmt.Exec(keyword)

	if err != nil {
		fmt.Println(err)
		return err
	}
	return nil

}
func SearchFailKey(keyword string) (error, bool) {
	var sql string

	sql = "select id from fail_keys where keyword='" + keyword + "';"
	NwayConn := nwayconnection.NewDb()
	rows, err := NwayConn.GetConn().Query(sql)
	defer rows.Close()
	var id int64
	if err == nil {
		for rows.Next() {
			err = rows.Scan(&id)
			if err != nil {
				fmt.Println(err)
			}
			return err, true
		}
		err = errors.New("not found cdr info")
	}
	return err, false
}
func main() {
	LoadKeyWord()
	NwayConn := nwayconnection.NewDb()
	bConnected := NwayConn.Init(DSTRING)
	fmt.Println(DSTRING)
	if bConnected == true {
		fmt.Println("Init database successed")
		NwayConn.GetConn()
	} else {
		fmt.Println("connect to database failed,close Nway_pbx")

		os.Exit(0)

	}
	mykeyword := strings.Split(NWAYWORD, ",")
	for _, word := range mykeyword {
		tmp := strings.TrimSpace(word)
		_, has := SearchFailKey(tmp)
		if has == false {
			InsertFailKey(tmp)
		}

	}

}
